﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDX.Services
{
    public class ServiceProvider : IServiceProvider
    {
        public ServiceProvider()
        {
            Entries = new Dictionary<Type, object>();
        }

        Dictionary<Type, object> Entries { get; set; }

        protected ServiceEntry<T> GetOrCreate<T>() where T : class
        {
            if (Entries.ContainsKey(typeof(T)))
            {
                return Entries[typeof(T)] as ServiceEntry<T>;
            }
            else
            {
                var entry = new ServiceEntry<T>();
                Entries[typeof(T)] = entry;
                return entry;
            }
        }

        public virtual T Resolve<T>() where T : class
        {
            return GetOrCreate<T>().Resolve();
        }

        public virtual IEnumerable<T> ResolveAll<T>() where T : class
        {
            return GetOrCreate<T>().ResolveAll();
        }

        public virtual void Register<T>(Func<T> Component) where T : class
        {
            GetOrCreate<T>().AddFactory(Component);
        }
    }
}
